package io.renren.modules.sys.controller;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import io.renren.common.utils.PageUtils;
import io.renren.common.utils.R;
import io.renren.common.utils.Tools;
import io.renren.common.validator.ValidatorUtils;
import io.renren.modules.sys.entity.AccountheadEntity;
import io.renren.modules.sys.service.AccountService;
import io.renren.modules.sys.service.AccountheadService;
import io.renren.modules.sys.service.PersonService;
import io.renren.modules.sys.service.SupplierService;
import net.sf.json.JSONObject;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Map;



/**
 * 财务主表
 *
 * @author chenshun
 * @email sunlightcs@gmail.com
 * @date 2018-11-22 14:29:35
 */
@RestController
@RequestMapping("sys/accounthead")
public class AccountheadController {

    protected static Logger logger = LoggerFactory.getLogger(AccountheadController.class);

    @Autowired
    private AccountheadService accountheadService;
    @Autowired
    private SupplierService supplierService;
    @Autowired
    private PersonService personService;
    @Autowired
    private AccountService accountService;

    /**
     * 列表
     */
    @RequestMapping("/list")
    @RequiresPermissions("sys:accounthead:list")
    public R list(@RequestParam Map<String, Object> params){
        PageUtils page = accountheadService.queryPage(params);

        return R.ok().put("page", page);
    }

    /**
     * 获取最大id
     * @return
     */
    @RequestMapping("getMaxId")
    public R getMaxId(){
        String maxId = accountheadService.getMaxId();
        return R.ok().put("maxId", maxId);
    }

    /**
     * 查找财务信息
     * findBy
     */
    @RequestMapping("findBy")
    public R findBy(@RequestParam Map<String, Object> params) {
        JSONObject outer = accountheadService.findFinancialInfo(params);
        logger.info("查找财务信息: " + outer);
        return R.ok().put("data", outer);
    }

    /**
     * 根据编号查询单据信息
     * @param params
     * @return
     */
    @RequestMapping("/getDetailByNumber")
    public JSONObject getDetailByNumber(@RequestParam Map<String, Object> params){
        List<AccountheadEntity> dataList = accountheadService.selectList(new EntityWrapper<AccountheadEntity>().eq("BillNo",params.get("BillNo").toString()));
        JSONObject item = new JSONObject();
        if (dataList != null && dataList.get(0) != null) {
            AccountheadEntity accountHead = dataList.get(0);
            item.put("Id", accountHead.getId());

            item.put("OrganId", accountHead.getOrganid() == null ? "" : supplierService.selectById(accountHead.getOrganid()) .getId());
            item.put("OrganName", accountHead.getOrganid() == null ? "" :  supplierService.selectById(accountHead.getOrganid()).getSupplier());
            item.put("HandsPersonId", accountHead.getHandspersonid() == null ? "" : personService.selectById(accountHead.getHandspersonid()).getId());
            item.put("HandsPersonName", accountHead.getHandspersonid() == null ? "" : personService.selectById(accountHead.getHandspersonid()).getName());
            item.put("AccountId", accountHead.getAccountid() == null ? "" :accountService.selectById(accountHead.getAccountid()).getId());
            item.put("AccountName", accountHead.getAccountid() == null ? "" : accountService.selectById(accountHead.getAccountid()).getName());
            item.put("BillNo", accountHead.getBillno());
            item.put("BillTime", Tools.getCenternTime(accountHead.getBilltime()));
            item.put("ChangeAmount", accountHead.getChangeamount() == null ? "" : Math.abs(accountHead.getChangeamount()));
            item.put("TotalPrice", accountHead.getTotalprice() == null ? "" : Math.abs(accountHead.getTotalprice()));
            item.put("Remark", accountHead.getRemark());
        }

        return item;
    }


    /**
     * 信息
     */
    @RequestMapping("/info/{id}")
    @RequiresPermissions("sys:accounthead:info")
    public R info(@PathVariable("id") Long id){
        AccountheadEntity accounthead = accountheadService.selectById(id);

        return R.ok().put("accounthead", accounthead);
    }

    /**
     * 保存
     * Type: 收入
     * BillNo: SR20181127155921
     * BillTime: 2018-11-27 15:59:21
     * AccountId: 10
     * ChangeAmount: 2000.00
     * TotalPrice: 1000.00
     * OrganId: 6
     * HandsPersonId: 3
     * Remark: 测试增加收入单信息
     */
    @RequestMapping("/save")
//    @RequiresPermissions("sys:accounthead:save")
    public R save(@RequestBody AccountheadEntity accounthead){
        accountheadService.insert(accounthead);
        return R.ok();
    }

    /**
     * 修改
     */
    @RequestMapping("/update")
//    @RequiresPermissions("sys:accounthead:update")
    public R update(@RequestBody AccountheadEntity accounthead){

        ValidatorUtils.validateEntity(accounthead);
        accountheadService.updateAllColumnById(accounthead);//全部更新
        
        return R.ok();
    }

    /**
     * 修改
     */
    @RequestMapping("/updateAH")
//    @RequiresPermissions("sys:accounthead:update")
    public R updateAH(@RequestBody AccountheadEntity accounthead, @RequestParam("accountHeadID") Long accountHeadId){
        accounthead.setId(accountHeadId);
        ValidatorUtils.validateEntity(accounthead);
        accountheadService.updateAllColumnById(accounthead);//全部更新

        return R.ok();
    }

    /**
     * 删除
     */
    @RequestMapping("/delete")
    @RequiresPermissions("sys:accounthead:delete")
    public R delete(@RequestBody Long[] ids){
        accountheadService.deleteBatchIds(Arrays.asList(ids));

        return R.ok();
    }

    /**
     * 删除
     */
    @RequestMapping("/batchDelete")
//    @RequiresPermissions("sys:accounthead:delete")
    public R batchDelete(@RequestParam("accountHeadIDs") String ids){
        String[] accountHeadIDs = ids.split(",");
        accountheadService.deleteBatchIds(Arrays.asList(accountHeadIDs));

        return R.ok();
    }


    @RequestMapping("/findTotalPay")
    public R findTotalPay(@RequestParam Map<String, Object> params) {

        String supType = Tools.dealNullStr(params.get("supType"));
        String getS = Tools.dealNullStr(params.get("supplierId"));
        String endTime = Tools.dealNullStr(params.get("EndTime"));

        int i=0;
        if ("customer".equals(supType)) { //客户
            i = 1;
        } else if ("vendor".equals(supType)) { //供应商
            i = -1;
        }

        Double sum = 0.0;
        //收付款部分
        sum = sum + (allMoney(getS, "付款", "合计",endTime) + allMoney(getS, "付款", "实际",endTime)) * i;
        sum = sum - (allMoney(getS, "收款", "合计",endTime) + allMoney(getS, "收款", "实际",endTime)) * i;
        sum = sum + (allMoney(getS, "收入", "合计",endTime) - allMoney(getS, "收入", "实际",endTime)) * i;
        sum = sum - (allMoney(getS, "支出", "合计",endTime) - allMoney(getS, "支出", "实际",endTime)) * i;

        return R.ok().put("getAllMoney",sum);
    }

    public Double allMoney(String getS, String type, String mode,String endTime) {
        Double sumNumber = 0.00;
        try {
            sumNumber= accountheadService.findAllMoney(getS, type,mode,endTime);
            if (sumNumber==null) {
                sumNumber = 0.00;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return sumNumber;
    }

}
